<template>
	<a-modal :visible="visible" width="90vw" centered destroyOnClose @cancel="exit" title="导入预览" :maskClosable="false">
		<div class="modal-comtainer">
			<div>总共上传{{ data.length }}条数据，校验失败{{ failData.length }}条，需全部数据校验成功才可导入</div>

			<a-row class="filter-bar">
				<a-col :span="4">
					<a-checkbox v-model:checked="params.filterFaile" @change="handleChangeFilter">仅筛选校验失败数据</a-checkbox>
				</a-col>
				<a-col :span="4">
					<a-checkbox v-model:checked="params.filterNotverified" @change="handleChangeFilter">仅筛选未核对账单数据</a-checkbox>
				</a-col>
				<a-col :span="2">
					<span>选择需隐藏内容:</span>
				</a-col>
				<a-col :span="6">
					<a-select
						class="filter-selector"
						placeholder="请选择"
						v-model:value="params.filterFieldList"
						max-tag-count="responsive"
						layout="'inline'"
						mode="multiple"
						allowClear
						:options="filterColumnList"></a-select>
				</a-col>
				<a-col :span="2">
					<a-button style="margin-left: 10px;" @click="handleCheckBill()" type="primary">批量核对账单</a-button>
				</a-col>
			</a-row>
			<vxe-grid v-bind="gridOptions" :header-cell-class-name="headerCellClassNname" :height="300" size="small" ref="grid">
				<template #idxNo="{row, rowIndex}">{{ rowIndex + 1 }}</template>
				<template #input="{row, column}">
					<a-input v-model:value="getTargetRow(row, column)[column.field]" allow-clear placeholder="请输入"></a-input>
				</template>
				<template #inputNumber="{row, column}">
					<a-input-number v-model:value="getTargetRow(row, column)[column.field]" :min="0" :precision="2" placeholder="请输入" />
				</template>
				<template #validate="{row}">
					<template v-if="row.errorList && row.errorList.length">
						<span v-color="{color: 'danger'}">{{ row.errorList.map(e => e.message).join('、') }}</span>
					</template>
					<template v-else-if="row.validationStatus == 2">
						<div v-color="{color: 'success'}">校验成功</div>
					</template>
				</template>
				<template #rentFreeDay="{row, column}">
					<a-button @click="(val, info) => changeFreeDay({val, info: {type: 'up'}}, getTargetRow(row, column), val)">+</a-button>
					<a-input-number
						v-model:value="getTargetRow(row, column)[column.field]"
						@step="(val, info) => changeFreeDay({val, info}, getTargetRow(row, column), val)"
						disabled
						:min="0"
						:max="getTargetRow(row, column).maxFreeNum"
						:precision="0"
						placeholder="请输入" />
					<a-button @click="(val, info) => changeFreeDay({val, info: {type: 'down'}}, getTargetRow(row, column), val)">
						-
					</a-button>
				</template>
				<template #selector="{row, column}">
					<a-select
						placeholder="请选择"
						v-model:value="getTargetRow(row, column)[column.field]"
						:options="getOptions(column.field)"
						@change="val => handleSelector(val, getTargetRow(row, column), column.field)"
						class="dept-emp-select"></a-select>
				</template>
				<template #datepicker="{row, column}">
					<a-range-picker
						v-model:value="getTargetRow(row, column)[column.field]"
						:format="formater.Date"
						:allowClear="false"
						@change="dates => handleChangeDatePicker(dates, getTargetRow(row, column))" />
				</template>
				<template #freeRange="{row, column}">
					{{ getFreeDayText(getTargetRow(row, column)) }}
					<!-- <a-range-picker disabled v-model:value="getTargetRow(row, column)[column.field]" :format="formater.Date" /> -->
				</template>
				<template #houseId="{row, column}">{{ getTargetRow(row, column).houseId }}</template>
				<template #houseAddress="{row, column}">{{ getTargetRow(row, column).houseAddress }}</template>
				<template #togetherList="{row, rowIndex, column}">
					<a-button type="primary" block @click="handleShowtogetherListDialog(row, rowIndex)">
						<template v-if="getTargetRow(row, column)[column.field].length">
							<check-outlined />
						</template>
						<plus-outlined v-else />
					</a-button>
				</template>
				<template #otherExpenses="{row, rowIndex, column}">
					<a-button type="primary" block @click="handleShowotherExpensesDialog(row, rowIndex)">
						<template v-if="getTargetRow(row, column)[column.field].length">
							<check-outlined />
						</template>
						<plus-outlined v-else />
					</a-button>
				</template>
				<template #signEmpId="{row, column}">
					<dept-emp-select
						v-if="getTargetRow(row, column).signDeptId && getTargetRow(row, column).signEmpId"
						:cache="true"
						v-model:dept-id="getTargetRow(row, column).signDeptId"
						v-model:emp-id="getTargetRow(row, column).signEmpId" />
					<dept-emp-select
						v-else
						:cache="true"
						v-model:dept-id="getTargetRow(row, column).signDeptId"
						v-model:emp-id="getTargetRow(row, column).signEmpId" />
				</template>
				<template #action="{row, rowIndex}">
					<span style="color: green" v-show="row.checkStatus" @click="handleShowBillPreviewDialog(row, rowIndex)">已核对</span>
					<a-button type="link" @click="handleShowBillPreviewDialog(row, rowIndex)" v-show="!row.checkStatus">核对账单</a-button>
					<a-button danger type="text" @click="handleDelete(row, rowIndex)">删除</a-button>
				</template>
			</vxe-grid>
		</div>
		<template #footer>
			<a-button @click="exit">退出</a-button>
			<a-button @click="save('edit')" type="primary">保存草稿并退出</a-button>
			<a-button @click="save('submit')" :loading="submitLoading" type="primary">确认导入</a-button>
		</template>
	</a-modal>
	<!-- 账单预览 -->
	<renter-bill-preview-dialog
		from="import"
		v-model:visible="billPreviewDialogConfig.visible"
		:id="billPreviewDialogConfig.id"
		:contract="billPreviewDialogConfig.row"
		@success="reflesh">
		<template #import_slot="{contract, billList}">
			<div style="width: 100%; display: flex; justify-content: space-between">
				<span>总金额：{{ countBillAnount(billList) }}</span>
				<a-button class="ml20" size="small" type="primary" @click="handleFinishBillCheck(billList)">已完成核对</a-button>
			</div>
		</template>
	</renter-bill-preview-dialog>
	<togetherListDialog
		v-model:visible="roomateDialogConfig.visible"
		v-model:data="roomateDialogConfig.row.togetherList"
		@success="reflesh"></togetherListDialog>
	<extreabudgetDialog
		v-model:visible="otherExpensesDialogConfig.visible"
		v-model:data="otherExpensesDialogConfig.row.otherExpenses"
		@addAll="handleAddAllbudget"
		@success="togetherListSuccess"></extreabudgetDialog>
</template>
<script setup lang="ts">
	import {CheckOutlined, PlusOutlined} from '@ant-design/icons-vue'
	import RenterBillPreviewDialog from '@/components/contract/tenant/renter-bill-preview-dialog.vue'
	import {onMounted, reactive, ref, watch, createVNode, computed, onUnmounted} from 'vue'
	import DeptEmpSelect from '@/components/common/dept-emp-select.vue'
	import {useStore} from '@/store/index'
	import {VxeGridProps, VxeGridInstance} from 'vxe-table'
	import {Form, message} from 'ant-design-vue'
	import {pagerConfig, proxyConfigProps} from 'yuxin-base/src/utils/vxe-table'
	import {columnList, selectOptionsConfig, filterColumnList} from './formConfig'
	import togetherListDialog from './togetherListDialog.vue'
	import extreabudgetDialog from './extreabudgetDialog.vue'
	import {defaultRenterContract, defaultRenterInfo, RenterContract, RenterContractDevice, RenterInfo} from '@/interface/contract'
	import {renterContractRules} from '@/rules/contract'
	import dayjs from 'dayjs'
	import {Modal} from 'ant-design-vue'
	import {checkImportContractBill,renterContractPreview, confirmImportContract, saveTmpImportContract, removeImportContract} from '@/api/contract'
	import XEUtils from 'xe-utils'
	import lodash from 'lodash'
	const store = useStore()
	onMounted(async () => {
		await store.getDeptOptions()
		// validateAlldata()
	})
	const emit = defineEmits(['update:visible', 'success'])
	const params: any = ref({
		filterFaile: false,
		filterNotverified: false,
		filterFieldList: []
	})
	const props = withDefaults(
		defineProps<{
			visible: boolean
			data?: any
			// 判断是否是审批
		}>(),
		{
			visible: false,
			data: {}
		}
	)
	const formater = {
		Date: 'YYYY-MM-DD'
	}
	const getOptions = fields => {
		if (!fields) return []
		return selectOptionsConfig[fields]
	}
	const rulesList = columnList.filter(e => e.required).map(e => XEUtils.pick(e, ['rule', 'field', 'title', 'required', 'inside']))
	const validateFn = data => {
		const errorList = rulesList
			.map(e => {
				const {rule, field, title, inside} = e
				const target = inside ? data[inside] : data
				let res = !!target[field]

				let messageStr = `未填写${title}`
				if (rule) {
					;(res = rule(target, field)), (messageStr = `${title}不合规`)
				}
				if (['contractRange'].includes(field)) {
					res = !!target[field]?.length
				}
				return {
					validate: res,
					message: messageStr
				}
			})
			.filter(e => !e.validate)
		return errorList
	}
	const filterColums: any = computed(() => {
		return columnList.filter((e: any) => !params.value.filterFieldList.includes(e.field))
	})
	const failData = ref([])
	const tabledata = props.data.map((e, index) => {
			const {renterInfo, beginTime, endTime, rentFreeDay} = e.renterContractForm
			if (!renterInfo) {
				e.renterContractForm.renterInfo = {}
				e.renterContractForm.renterInfo.__dataId = e.id
				e.renterContractForm.renterInfo.togetherList = e.renterContractForm.renterInfo.togetherList || []
			}
			if (renterInfo) {
				e.renterContractForm.renterInfo.__dataId = e.id
				e.renterContractForm.renterInfo.togetherList = e.renterContractForm.renterInfo.togetherList || []
			}
			e.renterContractForm.otherExpenses = e.renterContractForm.otherExpenses || []
			e.renterContractForm.zeroRentPeriod = 4
			e.idxNo = index + 1
			e.renterContractForm.__dataId = e.id
			if (beginTime && endTime) {
				e.renterContractForm.contractRange = [dayjs(beginTime, formater.Date), dayjs(endTime, formater.Date)]
				e.renterContractForm.freeRange = [dayjs(beginTime).subtract(rentFreeDay, 'day'), dayjs(beginTime).subtract(1, 'day')]
			} else {
				e.renterContractForm.contractRange = []
				e.renterContractForm.freeRange = []
			}
			const errorList = validateFn(e.renterContractForm)
			e.errorList = errorList
			console.log(111)

			return {
				...e
			}
		})
	const filterData: any = computed(() => {
		const {filterFaile, filterNotverified} = params.value
		return tabledata.filter(e => {
			let res = true
			if (filterFaile && !filterNotverified) {
				res = e.failReason || e.errorList?.length
			} else if (filterNotverified && !filterFaile) {
				res = !e.checkStatus
			} else if (filterFaile && filterNotverified) {
				res = !e.checkStatus || e.failReason || e.errorList?.length
			}
			return res
		})
	})


	watch(
		() => tabledata,
		val => {
			console.log(111)

			failData.value = val.filter(e => e.failReason || (e.errorList && e.errorList.length))
		},
		{
			deep: true,
			immediate:true,
			onTrigger: event => {
				const {key, target} = event
				if (['freeRange', 'contractRange'].includes(key)) {
					return
				}
				if (target?.__dataId) {
					const currentData = tabledata.find(e => e.id === target?.__dataId) || {}
					const errorList = validateFn(currentData.renterContractForm)
					currentData.errorList = errorList
					grid.value?.updateData()
					console.log(event)

					if(currentData.checkStatus !==1) {
						currentData.errorList.push({
							validate: false,
							message: '账单未核对'
						})
					}

					// if(errorList.length) {
					// 	currentData.validationStatus = 1
					// 	currentData.failReason = errorList
					// 	grid.value?.updateData()
					// } else {
					// 	currentData.validationStatus = 2
					// 	currentData.failReason = null
					// }
				}
			}
		}
	)
	watch([() => props.data, () => props.visible], val => {
		if (val) {
			validateAlldata()
		}
	})
	const headerCellClassNname = params => {
		const {
			column: {field}
		} = params
		const {required} = columnList.find(e => e.field === field) || {}

		return required ? 'required' : ''
	}
	// 免租期最大可填写
	const maxFreeNum = ref<number>(360)
	const gridOptions = reactive<VxeGridProps>({
		height: 'auto',
		showOverflow: true,
		rowConfig: {
			isHover: true
		},
		columns: filterColums,
		scrollY: {
			enabled: true,
			gt: 5,
			oSize: 15
		},
		data: filterData

		// pagerConfig:{
		// 	...pagerConfig,
		// 	pageSizes:[10,15,20,25]
		// },

		// proxyConfig: {
		// 	props: {
		// 		// 用于列表，读取响应数据，不分页
		// 		list: 'data',
		// 		message: 'msg',
		// 		// 用于分页，读取总条数
		// 		total: 'data.total',
		// 		// 用于分页，读取响应数据
		// 		result: 'data.records'
		// 	},
		// 	ajax: {
		// 		query({page: {currentPage: current, pageSize: size}}) {
		// 			console.log(current,size)
		// 			const total = filterData.value.length
		// 			const chunkList = lodash.chunk(filterData.value,size)
		// 			console.log(lodash.chunk(filterData.value,size),'lodash.chunk(filterData.value,size)');

		// 			return {data: {records: chunkList[current -1], total}}
		// 			// return queryData({...params, current, size})
		// 		}
		// 	}
		// }
	})
	const queryData = (params: any) => {
		// houseConfigListState(params).then((res: any) => {
		// 	countObj.value = res.data || {}
		// })
		return
	}
	const grid = ref<VxeGridInstance>()
	const getList = (page?: any) => {
		grid.value?.commitProxy(page === 1 ? 'reload' : 'query')
	}

	const getFreeDayText = row => {
		return row.freeRange.length && row.rentFreeDay
			? `${dayjs(row.freeRange[0]).format(formater.Date)}-${dayjs(row.freeRange[1]).format(formater.Date)}`
			: '-'
	}
	const handleDelete = (row: any, rowIndex: any) => {
		Modal.confirm({
			title: '系统提示',
			content: '确定要退出吗?退出后需要重新导入数据',
			okText: '确定',
			cancelText: '取消',
			onOk() {
				console.log(row, rowIndex)
				const idx = tabledata.findIndex(e => e.id === row.id)
				filterData.value.splice(rowIndex, 1)
				tabledata.splice(idx, 1)
				grid.value?.reloadData(filterData.value)
			},
			onCancel() {
				console.log('Cancel')
			}
		})
	}
	const roomateDialogConfig: any = ref({
		visible: false,
		rowIndex: 0,
		row: {}
	})
	const billPreviewDialogConfig: any = ref({
		visible: false,
		rowIndex: 0,
		row: {}
	})
	const otherExpensesDialogConfig: any = ref({
		visible: false,
		rowIndex: 0,
		row: {}
	})
	const countBillAnount = list => {
		return (
			list.reduce((res, acc) => {
				acc.bills.forEach(item => {
					res += item.totalAmount * 1000
				})
				return res
			}, 0) / 1000
		)
	}
	const handleFinishBillCheck = billList => {
		const {rowIndex, id, row} = billPreviewDialogConfig.value
		filterData.value[rowIndex].renterContractForm.billInfos = billList

		checkImportContractBill({id, renterContractForm: row}).then(({data = []}) => {
			console.log(data)
			if (data) {
				const idx = tabledata.findIndex(e => e.id === id)
				filterData.value[rowIndex].checkStatus = 1
				tabledata[idx].checkStatus = 1
				billPreviewDialogConfig.value.visible = false
				grid.value?.reloadData(filterData.value)
			}
		})
	}
	const handleSelector = (val, row, field) => {
		if (field === 'depositMonth') {
			row.deposit = XEUtils.multiply(row.price, row.depositMonth)
		}
	}
	const reflesh = () => {
		grid.value?.reloadData(filterData.value)
	}
	const handleShowtogetherListDialog = (row, rowIndex) => {
		roomateDialogConfig.value = {
			row: row.renterContractForm.renterInfo,
						rowIndex,
			visible: true
		}
	}
	const handleChangeDatePicker = (dates, row) => {
		dates = dates || []
		if (dates[0] != row.beginTime) {
			row.rentFreeDay = 0
		}
		row.beginTime = dayjs(dates[0]).format(formater.Date)
		row.endTime = dayjs(dates[1]).format(formater.Date)

		if ([1].includes(row.signType)) {
			row.maxFreeNum = dayjs(row.endTime).diff(dayjs(row.beginTime), 'day')
		}
	}
	const changeFreeDay = (origin, row, val) => {
		const {
			info: {type}
		} = origin

		if (row.signType === 1) {
			//新签
			if (type === 'up') {
				row.rentFreeDay += 1
				row.beginTime = dayjs(row.beginTime).add(1, 'day').format(formater.Date)
				row.endTime = dayjs(row.endTime).add(1, 'day').format(formater.Date)
			} else {
				if (row.rentFreeDay >= 1) {
					row.rentFreeDay -= 1
					row.beginTime = dayjs(row.beginTime).subtract(1, 'day').format(formater.Date)
					row.endTime = dayjs(row.endTime).subtract(1, 'day').format(formater.Date)
				}
			}
		}

		row.contractRange = [dayjs(row.beginTime), dayjs(row.endTime)]
		row.freeRange = [dayjs(row.beginTime).subtract(row.rentFreeDay, 'day'), dayjs(row.beginTime).subtract(1, 'day')]
	}
	const handleShowBillPreviewDialog = (row, rowIndex) => {
		billPreviewDialogConfig.value = {
			row: row.renterContractForm,
			id: row.id,
			rowIndex,
			visible: true
		}
	}

	const handleAddAllbudget = data => {
		filterData.value.forEach(e => {
			e.checkStatus =0
			e.renterContractForm.otherExpenses = XEUtils.clone(data, true)
		})
		grid.value?.reloadData(filterData.value)
		validateAlldata()
	}
	const handleShowotherExpensesDialog = (row, rowIndex) => {
		otherExpensesDialogConfig.value = {
			row: row.renterContractForm,
			rowIndex,
			visible: true
		}
	}
	const getTargetRow = (row, column) => {
		const {inside} = columnList.find(e => e.field === column.field) || {}

		if (inside) {
			return row.renterContractForm[inside]
		}
		return row.renterContractForm
	}
	const handleChangeFilter = () => {
		grid.value?.reloadData(filterData.value)
	}
	const exit = () => {
		Modal.confirm({
			title: '系统提示',
			content: '确定要退出吗？退出后需要重新导入数据',
			centered: true,
			onOk() {
				removeImportContract({}).then(res => {
					message.success('操作成功')
					emit('success')
					cancel()
				})
			}
		})
	}
	const validateAlldata = () => {
		tabledata.forEach(e => {
			const errorList = validateFn(e.renterContractForm)
			e.errorList = errorList
			if(e.checkStatus !==1) {
				e.errorList.push({
							validate: false,
							message: '账单未核对'
						})
					}
		})
		failData.value = tabledata.filter(e => e.failReason || (e.errorList && e.errorList.length))
		grid.value?.updateData()
	}
	const submitLoading = ref(false)
	const save = type => {
		if (type === 'submit') {
			submitLoading.value = true
			validateAlldata()
			const failList = tabledata.filter(e => e.failReason || e.errorList?.length)
			const checkStatusList = tabledata.filter(e => e.checkStatus !== 1 )
			submitLoading.value = false
			if (failList.length) {
				message.error('校验有误，请检查')
				return
			}
			if (checkStatusList.length) {
				message.error('还有账单没核对，请检查')
				return
			}
			Modal.confirm({
				title: '系统提示',
				content: '数据已提交处理，当前可关闭页面，处理结果可在导入历史中查看',
				centered: true,
				onOk() {
					confirmImportContract(tabledata).then(res => {
						message.success('导入成功')
						emit('success')
						cancel()
					})
				}
			})
		}
		if (type === 'edit') {
			saveTmpImportContract(tabledata).then(res => {
				message.success('操作成功')
				emit('success')
				cancel()
			})
		}
	}
	const cancel = () => {
		emit('update:visible', false)
	}
	const togetherListSuccess = () => {
		const id = otherExpensesDialogConfig.value.row.__dataId
		console.log(otherExpensesDialogConfig.value,'id')
		const tar = tabledata.find(e=>e.id === id)
		tar.checkStatus = 0

		validateAlldata()
		reflesh()
	}
	const handleCheckBill = async () =>{
		for (let index = 0; index < tabledata.length; index++) {
			const target = tabledata[index]
			const data = tabledata[index].renterContractForm
			const params = {
			isCustomize: 0,
			// 合同id 只在修改重新签约时传
			contractId: data.contractId,
			contractPid: data.contractPid,
			carryForward: data.carryForward,
			carryForwardPrice: Math.abs(data.deductionAmount || 0),
			// 结转方式 1:先抵再折 2:先折再抵(换房先折再抵 其余的先抵再折)
			carryForwardMode: 4 === data.signType ? 2 : 1,
			beginTime: data.beginTime,
			endTime: data.endTime,
			payPattern: data.payPattern,
			payPatternValue: data.payPatternValue,
			depositMonth: data.depositMonth,
			periodMonth: data.periodMonth,
			price: data.price,
			deposit: data.deposit,
			oldDeposit: data.oldDeposit,
			signType: data.signType === 2 ? 2 : 1,
			cycleType: data.cycleType,
			mergeType: data.mergeType,
			otherExpenses: data.otherExpenses,
			zeroRentPeriod: data.zeroRentPeriod,
			houseId: data.houseId,
			// 手机号判断是否有预定，用于定金抵扣
			phone: data.renterInfo?.phone,
			discountIds: data.discountIds ?? []
		}
		const res = await renterContractPreview(params)
		console.log(res,'renterContractPreview')
		data.billInfos = res.data
		target.checkStatus = 1
		}

		validateAlldata()


	}
</script>
<style lang="less">
	.modal-comtainer {
		padding: 30px 20px;
	}

	.red {
		color: red;
	}

	.filter-bar {
		display: flex;
		align-items: center;
		margin: 15px 0;
	}

	.filter-selector {
		width: 100%;
	}

	.required .vxe-cell::after {
		content: '*';
		display: inline-block;
		color: red;
	}
</style>
